import { useNavigate } from 'react-router-dom';
import { useState, useMemo } from 'react';
import { ShoppingCart, Trash2, ArrowRight, Package, ChevronLeft, ChevronRight, ArrowLeft as BackArrow } from 'lucide-react';
import { useCart } from '../../contexts/CartContext';
import { useLanguage } from '@kernelproxy/i18n';
import { StripePaymentModal } from '../../components/StripePaymentModal';
import { orderService } from '../../services/order';
import { useToast } from '../../contexts/ToastContext';


const ITEMS_PER_PAGE = 5;

const Cart = () => {
  const { items, removeItem, clearCart, getTotalPrice } = useCart();
  const { language } = useLanguage();
  const navigate = useNavigate();
  const toast = useToast();
  const [currentPage, setCurrentPage] = useState(1);
  const [showStripePayment, setShowStripePayment] = useState(false);
  const [isCreatingOrder, setIsCreatingOrder] = useState(false);
  
  const getLink = (path: string) => {
    return language === 'zh-CN' ? `/zh-CN${path}` : path;
  };
  
  // Coupon code state
  const [couponCode, setCouponCode] = useState('');
  const [appliedCoupon, setAppliedCoupon] = useState<string | null>(null);
  const [couponDiscount, setCouponDiscount] = useState(0);
  const [isCouponApplying, setIsCouponApplying] = useState(false);

  // Calculate pagination
  const totalPages = Math.ceil(items.length / ITEMS_PER_PAGE);
  const startIndex = (currentPage - 1) * ITEMS_PER_PAGE;
  const endIndex = startIndex + ITEMS_PER_PAGE;
  const currentItems = useMemo(() => items.slice(startIndex, endIndex), [items, startIndex, endIndex]);

  // Reset to page 1 if current page is out of bounds
  useMemo(() => {
    if (currentPage > totalPages && totalPages > 0) {
      setCurrentPage(totalPages);
    }
  }, [currentPage, totalPages]);

  // Apply coupon code
  const handleApplyCoupon = () => {
    setIsCouponApplying(true);
    
    setTimeout(() => {
      const validCoupons: Record<string, number> = {
        'SAVE10': 0.10,
        'SAVE20': 0.20,
        'WELCOME': 0.15,
        'VIP': 0.25,
      };
      
      const discount = validCoupons[couponCode.toUpperCase()];
      
      if (discount) {
        setAppliedCoupon(couponCode.toUpperCase());
        setCouponDiscount(discount);
        alert(language === 'zh-CN' 
          ? `优惠码已应用！享受 ${(discount * 100).toFixed(0)}% 折扣`
          : `Coupon applied! Enjoy ${(discount * 100).toFixed(0)}% off`
        );
      } else {
        alert(language === 'zh-CN' ? '无效的优惠码' : 'Invalid coupon code');
      }
      
      setIsCouponApplying(false);
    }, 500);
  };

  // Remove coupon
  const handleRemoveCoupon = () => {
    setAppliedCoupon(null);
    setCouponDiscount(0);
    setCouponCode('');
  };

  // Calculate final price with discount
  const subtotal = getTotalPrice();
  const discountAmount = subtotal * couponDiscount;
  const finalTotal = subtotal - discountAmount;

  // Handle place order - create order and navigate to orders page
  const handlePlaceOrder = async () => {
    if (items.length === 0) {
      toast.error(language === 'zh-CN' ? '购物车为空' : 'Cart is empty');
      return;
    }

    // Check minimum amount
    if (finalTotal < 0.5) {
      toast.error(language === 'zh-CN' ? '最低支付金额为 $0.50' : 'Minimum payment amount is $0.50');
      return;
    }

    setIsCreatingOrder(true);
    try {
      const orderItems = items.map(item => ({
        id: item.id,
        productType: item.productType,
        productName: getProductName(item.productType),
        quantity: typeof item.quantity === 'number' ? item.quantity : 1,
        price: item.totalPrice,
        period: item.period,
        traffic: item.traffic,
        ips: typeof item.quantity === 'number' ? item.quantity : undefined,
      }));

      const result = await orderService.createOrder({
        items: orderItems,
        total: finalTotal,
        couponCode: appliedCoupon || undefined,
        discount: discountAmount,
      });

      if (result.success && result.order) {
        toast.success(language === 'zh-CN' ? '订单创建成功！' : 'Order created successfully!');
        clearCart();
        // Navigate to order detail page
        navigate(getLink(`/dashboard/orders?id=${result.order.id}`));
      } else {
        toast.error(result.error || (language === 'zh-CN' ? '创建订单失败' : 'Failed to create order'));
      }
    } catch (error) {
      console.error('Error creating order:', error);
      toast.error(language === 'zh-CN' ? '创建订单失败' : 'Failed to create order');
    } finally {
      setIsCreatingOrder(false);
    }
  };

  // Handle successful payment
  const handlePaymentSuccess = () => {
    clearCart();
    setShowStripePayment(false);
    toast.success(language === 'zh-CN' ? '支付成功！订单已创建。' : 'Payment successful! Order created.');
    // Navigate to orders page
    navigate(getLink('/dashboard/orders'));
  };

  const getProductName = (productType: string) => {
    const names = {
      'dynamic-residential': {
        en: 'Dynamic Residential IPv6',
        'zh-CN': '动态住宅 IPv6',
      },
      'static-residential': {
        en: 'Static Residential IPv6',
        'zh-CN': '静态住宅 IPv6',
      },
      'datacenter': {
        en: 'Datacenter IPv6',
        'zh-CN': '数据中心 IPv6',
      },
    };
    return names[productType as keyof typeof names]?.[language] || productType;
  };

  const getPeriodLabel = (period?: string) => {
    if (!period) return '';
    const labels = {
      day: { en: 'Daily', 'zh-CN': '按天' },
      week: { en: 'Weekly', 'zh-CN': '按周' },
      month: { en: 'Monthly', 'zh-CN': '按月' },
      year: { en: 'Yearly', 'zh-CN': '按年' },
    };
    return labels[period as keyof typeof labels]?.[language] || period;
  };

  if (items.length === 0) {
    return (
      <div className="space-y-6">
        <div>
          <button
            onClick={() => navigate(getLink('/dashboard'))}
            className="flex items-center text-gray-600 dark:text-gray-400 hover:text-blue-600 dark:hover:text-blue-400 mb-2 transition-colors"
          >
            <BackArrow size={20} className="mr-2" />
            {language === 'zh-CN' ? '返回概览' : 'Back to Overview'}
          </button>
          <h1 className="text-3xl font-bold text-gray-900 dark:text-white">
            {language === 'zh-CN' ? '购物车' : 'Shopping Cart'}
          </h1>
        </div>

        <div className="bg-white dark:bg-gray-800 rounded-xl p-12 text-center shadow-lg">
          <div className="inline-flex items-center justify-center w-24 h-24 bg-gray-100 dark:bg-gray-700 rounded-full mb-6">
            <ShoppingCart className="text-gray-400 dark:text-gray-500" size={48} />
          </div>
          <h2 className="text-2xl font-bold text-gray-900 dark:text-white mb-4">
            {language === 'zh-CN' ? '购物车为空' : 'Your cart is empty'}
          </h2>
          <p className="text-gray-600 dark:text-gray-300 mb-8">
            {language === 'zh-CN'
              ? '浏览我们的产品并添加您需要的服务'
              : 'Browse our products and add the services you need'}
          </p>
          <button
            onClick={() => navigate(getLink('/dashboard'))}
            className="bg-gradient-to-r from-blue-600 to-purple-600 text-white py-3 px-8 rounded-lg hover:from-blue-700 hover:to-purple-700 transition-all duration-300 font-semibold"
          >
            {language === 'zh-CN' ? '开始选购' : 'Start Shopping'}
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <div className="flex justify-between items-center">
        <div>
          <button
            onClick={() => navigate(getLink('/dashboard'))}
            className="flex items-center text-gray-600 dark:text-gray-400 hover:text-blue-600 dark:hover:text-blue-400 mb-2 transition-colors"
          >
            <BackArrow size={20} className="mr-2" />
            {language === 'zh-CN' ? '返回概览' : 'Back to Overview'}
          </button>
          <h1 className="text-3xl font-bold text-gray-900 dark:text-white">
            {language === 'zh-CN' ? '购物车' : 'Shopping Cart'}
            <span className="ml-3 text-lg font-normal text-gray-500 dark:text-gray-400">
              ({items.length} {language === 'zh-CN' ? '件商品' : 'items'})
            </span>
          </h1>
        </div>
        <button
          onClick={clearCart}
          className="text-red-600 hover:text-red-700 dark:text-red-400 dark:hover:text-red-300 flex items-center gap-2 transition-colors"
        >
          <Trash2 size={18} />
          {language === 'zh-CN' ? '清空购物车' : 'Clear Cart'}
        </button>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Cart Items */}
        <div className="lg:col-span-2 space-y-6">
          <div className="space-y-4">
            {currentItems.map((item) => (
              <div
                key={item.id}
                className="bg-white dark:bg-gray-800 rounded-xl p-6 shadow-md border border-gray-200 dark:border-gray-700 transition-colors"
              >
                <div className="flex justify-between items-start">
                  <div className="flex-1">
                    <div className="flex items-start justify-between mb-4">
                      <div>
                        <h3 className="text-lg font-bold text-gray-900 dark:text-white mb-2">
                          {getProductName(item.productType)}
                        </h3>
                        <div className="space-y-1 text-sm text-gray-600 dark:text-gray-300">
                          {item.productType === 'dynamic-residential' && item.traffic && (
                            <div className="flex items-center gap-2">
                              <Package size={16} />
                              <span>
                                {language === 'zh-CN' ? '流量：' : 'Traffic: '}
                                {item.traffic} GB
                              </span>
                            </div>
                          )}

                          {(item.productType === 'static-residential' || item.productType === 'datacenter') && (
                            <>
                              {item.quantity && (
                                <div>
                                  {language === 'zh-CN' ? '数量：' : 'Quantity: '}
                                  {item.quantity} IP{item.quantity > 1 ? 's' : ''}
                                </div>
                              )}
                              {item.period && (
                                <div>
                                  {language === 'zh-CN' ? '计费周期：' : 'Period: '}
                                  {getPeriodLabel(item.period)}
                                </div>
                              )}
                              {item.countryName && (
                                <div>
                                  {language === 'zh-CN' ? '国家：' : 'Country: '}
                                  {item.countryName}
                                </div>
                              )}
                            </>
                          )}

                          {item.discount && item.discount > 0 && (
                            <div className="text-green-600 dark:text-green-400">
                              {language === 'zh-CN' ? '折扣：' : 'Discount: '}
                              {(item.discount * 100).toFixed(0)}% OFF
                            </div>
                          )}
                        </div>
                      </div>

                      <button
                        onClick={() => removeItem(item.id)}
                        className="text-red-600 hover:text-red-700 dark:text-red-400 dark:hover:text-red-300 p-2 rounded-lg hover:bg-red-50 dark:hover:bg-red-900/20 transition-colors"
                        title={language === 'zh-CN' ? '移除' : 'Remove'}
                      >
                        <Trash2 size={18} />
                      </button>
                    </div>

                    <div className="flex justify-between items-center pt-4 border-t border-gray-200 dark:border-gray-700">
                      <div className="text-sm text-gray-500 dark:text-gray-400">
                        {language === 'zh-CN' ? '单价：' : 'Unit Price: '}
                        <span className="font-medium text-gray-900 dark:text-white">
                          ${item.unitPrice.toFixed(2)}
                        </span>
                      </div>
                      <div className="text-xl font-bold text-gray-900 dark:text-white">
                        ${item.totalPrice.toFixed(2)}
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            ))}
          </div>

          {/* Pagination Controls */}
          {totalPages > 1 && (
            <div className="flex justify-center items-center gap-4">
              <button
                onClick={() => setCurrentPage(p => Math.max(1, p - 1))}
                disabled={currentPage === 1}
                className="flex items-center gap-2 px-4 py-2 rounded-lg bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
              >
                <ChevronLeft size={18} />
                <span>{language === 'zh-CN' ? '上一页' : 'Prev'}</span>
              </button>
              
              <span className="text-sm text-gray-600 dark:text-gray-400">
                {language === 'zh-CN' 
                  ? `第 ${currentPage} 页，共 ${totalPages} 页` 
                  : `Page ${currentPage} of ${totalPages}`}
              </span>
              
              <button
                onClick={() => setCurrentPage(p => Math.min(totalPages, p + 1))}
                disabled={currentPage === totalPages}
                className="flex items-center gap-2 px-4 py-2 rounded-lg bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
              >
                <span>{language === 'zh-CN' ? '下一页' : 'Next'}</span>
                <ChevronRight size={18} />
              </button>
            </div>
          )}
        </div>

        {/* Order Summary */}
        <div className="lg:col-span-1">
          <div className="bg-gradient-to-br from-gray-900 to-gray-800 dark:from-gray-800 dark:to-gray-900 rounded-xl p-6 shadow-lg text-white sticky top-24">
            <h3 className="text-xl font-bold mb-6">
              {language === 'zh-CN' ? '订单摘要' : 'Order Summary'}
            </h3>

            <div className="space-y-4 mb-6">
              <div className="flex justify-between text-sm">
                <span className="text-gray-300">
                  {language === 'zh-CN' ? '商品数量' : 'Items'}:
                </span>
                <span className="font-medium">{items.length}</span>
              </div>

              <div className="flex justify-between text-sm">
                <span className="text-gray-300">
                  {language === 'zh-CN' ? '小计' : 'Subtotal'}:
                </span>
                <span className="font-medium">${subtotal.toFixed(2)}</span>
              </div>

              {/* Coupon Code Section */}
              <div className="border-t border-white/20 pt-4">
                {!appliedCoupon ? (
                  <div className="space-y-2">
                    <label className="block text-xs text-gray-300 font-medium">
                      {language === 'zh-CN' ? '优惠码' : 'Coupon Code'}
                    </label>
                    <div className="flex gap-2">
                      <input
                        type="text"
                        value={couponCode}
                        onChange={(e) => setCouponCode(e.target.value.toUpperCase())}
                        placeholder={language === 'zh-CN' ? '输入优惠码' : 'Enter code'}
                        className="flex-1 px-3 py-2 bg-white/10 border border-white/30 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-600 focus:border-transparent text-white placeholder-gray-400 text-sm"
                      />
                      <button
                        onClick={handleApplyCoupon}
                        disabled={!couponCode || isCouponApplying}
                        className="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white font-semibold rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed text-sm whitespace-nowrap"
                      >
                        {isCouponApplying 
                          ? (language === 'zh-CN' ? '应用中...' : 'Applying...') 
                          : (language === 'zh-CN' ? '应用' : 'Apply')
                        }
                      </button>
                    </div>
                  </div>
                ) : (
                  <div className="space-y-2">
                    <div className="flex items-center justify-between p-2 bg-green-500/20 border border-green-500/30 rounded-lg">
                      <div className="flex items-center gap-2">
                        <svg className="w-4 h-4 text-green-400" fill="currentColor" viewBox="0 0 20 20">
                          <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clipRule="evenodd" />
                        </svg>
                        <span className="text-sm text-green-400 font-medium">{appliedCoupon}</span>
                      </div>
                      <button
                        onClick={handleRemoveCoupon}
                        className="text-xs text-gray-300 hover:text-white underline"
                      >
                        {language === 'zh-CN' ? '移除' : 'Remove'}
                      </button>
                    </div>
                  </div>
                )}
              </div>

              {appliedCoupon && (
                <div className="flex justify-between text-sm">
                  <span className="text-green-400">
                    {language === 'zh-CN' ? '折扣' : 'Discount'} ({(couponDiscount * 100).toFixed(0)}%):
                  </span>
                  <span className="font-medium text-green-400">-${discountAmount.toFixed(2)}</span>
                </div>
              )}

              <div className="border-t border-white/20 pt-4">
                <div className="flex justify-between text-lg font-bold">
                  <span>{language === 'zh-CN' ? '总计' : 'Total'}:</span>
                  <span className="text-blue-400">${finalTotal.toFixed(2)}</span>
                </div>
              </div>
            </div>

            <button
              onClick={handlePlaceOrder}
              disabled={isCreatingOrder || items.length === 0}
              className="w-full mb-3 px-6 py-3 bg-blue-600 hover:bg-blue-700 dark:bg-blue-500 dark:hover:bg-blue-600 text-white rounded-lg font-semibold transition-all flex items-center justify-center gap-2 shadow-lg disabled:opacity-50 disabled:cursor-not-allowed"
            >
              {isCreatingOrder ? (
                <>
                  <div className="animate-spin rounded-full h-5 w-5 border-b-2 border-white"></div>
                  {language === 'zh-CN' ? '创建中...' : 'Creating...'}
                </>
              ) : (
                <>
                  {language === 'zh-CN' ? '下单' : 'Place an Order'}
                  <ArrowRight size={18} />
                </>
              )}
            </button>

            <button
              onClick={() => navigate(getLink('/dashboard'))}
              className="w-full text-center text-sm text-gray-300 hover:text-white transition-colors"
            >
              {language === 'zh-CN' ? '继续购物' : 'Continue Shopping'}
            </button>
          </div>
        </div>
      </div>

      {/* Stripe Payment Modal */}
      <StripePaymentModal
        isOpen={showStripePayment}
        onSuccess={handlePaymentSuccess}
        onClose={() => setShowStripePayment(false)}
        amount={finalTotal}
      />
    </div>
  );
};

export default Cart;
